<template>
  <div class="meeting-room-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>会议室管理</span>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            添加会议室
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-input
              v-model="searchForm.name"
              placeholder="会议室名称"
              clearable
              @input="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-select
              v-model="searchForm.status"
              placeholder="状态"
              clearable
              @change="handleSearch"
          >
            <el-option label="可用" value="available" />
            <el-option label="维护中" value="maintenance" />
            <el-option label="已停用" value="disabled" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
              v-model="searchForm.capacity"
              placeholder="容纳人数"
              clearable
              @change="handleSearch"
          >
            <el-option label="1-5人" value="small" />
            <el-option label="6-10人" value="medium" />
            <el-option label="11-20人" value="large" />
            <el-option label="20人以上" value="extra-large" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>

      <!-- 会议室列表 -->
      <el-table :data="filteredRooms" style="width: 100%">
        <el-table-column prop="name" label="会议室名称" width="150" />
        <el-table-column prop="location" label="位置" width="120" />
        <el-table-column prop="capacity" label="容纳人数" width="100" />
        <el-table-column prop="equipment" label="设备配置" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑会议室对话框 -->
    <el-dialog
        v-model="showAddDialog"
        :title="isEdit ? '编辑会议室' : '添加会议室'"
        width="600px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="会议室名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入会议室名称" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入位置" />
        </el-form-item>
        <el-form-item label="容纳人数" prop="capacity">
          <el-input-number
              v-model="form.capacity"
              :min="1"
              :max="100"
              placeholder="请输入容纳人数"
          />
        </el-form-item>
        <el-form-item label="设备配置" prop="equipment">
          <el-checkbox-group v-model="form.equipment">
            <el-checkbox label="投影仪" />
            <el-checkbox label="白板" />
            <el-checkbox label="音响" />
            <el-checkbox label="视频会议" />
            <el-checkbox label="空调" />
            <el-checkbox label="WiFi" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="可用" value="available" />
            <el-option label="维护中" value="maintenance" />
            <el-option label="已停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 会议室数据
const rooms = ref([
  {
    id: 1,
    name: '会议室A',
    location: '1楼101',
    capacity: 10,
    equipment: ['投影仪', '白板', '音响'],
    status: 'available',
    description: '标准会议室，适合小型会议'
  },
  {
    id: 2,
    name: '会议室B',
    location: '2楼201',
    capacity: 20,
    equipment: ['投影仪', '白板', '音响', '视频会议'],
    status: 'available',
    description: '大型会议室，适合团队会议'
  },
  {
    id: 3,
    name: '会议室C',
    location: '3楼301',
    capacity: 5,
    equipment: ['白板', 'WiFi'],
    status: 'maintenance',
    description: '小型会议室，适合一对一会议'
  }
])

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  capacity: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(rooms.value.length)

// 对话框
const showAddDialog = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: 0,
  name: '',
  location: '',
  capacity: 10,
  equipment: [],
  status: 'available',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入会议室名称', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入位置', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入容纳人数', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 过滤后的会议室列表
const filteredRooms = computed(() => {
  let result = rooms.value

  if (searchForm.name) {
    result = result.filter(room =>
        room.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }

  if (searchForm.status) {
    result = result.filter(room => room.status === searchForm.status)
  }

  if (searchForm.capacity) {
    result = result.filter(room => {
      const capacity = room.capacity
      switch (searchForm.capacity) {
        case 'small': return capacity <= 5
        case 'medium': return capacity > 5 && capacity <= 10
        case 'large': return capacity > 10 && capacity <= 20
        case 'extra-large': return capacity > 20
        default: return true
      }
    })
  }

  return result
})

// 获取状态类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    available: 'success',
    maintenance: 'warning',
    disabled: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    available: '可用',
    maintenance: '维护中',
    disabled: '已停用'
  }
  return texts[status] || '未知'
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = ''
  searchForm.capacity = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 编辑会议室
const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(form, row)
  showAddDialog.value = true
}

// 删除会议室
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
      `确定要删除会议室"${row.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    const index = rooms.value.findIndex(room => room.id === row.id)
    if (index > -1) {
      rooms.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (isEdit.value) {
      // 编辑
      const index = rooms.value.findIndex(room => room.id === form.id)
      if (index > -1) {
        Object.assign(rooms.value[index], { ...form })
      }
      ElMessage.success('编辑成功')
    } else {
      // 添加
      const newRoom = {
        ...form,
        id: Date.now()
      }
      rooms.value.push(newRoom)
      ElMessage.success('添加成功')
    }

    showAddDialog.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: 0,
    name: '',
    location: '',
    capacity: 10,
    equipment: [],
    status: 'available',
    description: ''
  })
  isEdit.value = false
}
</script>

<style scoped lang="scss">
.meeting-room-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>